import * as Cesium from 'cesium';

export async function createFlightAnimation(viewer, geoJsonUrl, modelUrl, duration = 600) {
  // 1. 加载飞行路径
  const loadFlightPath = async () => {
    try {
      const response = await fetch(geoJsonUrl);
      const geoJson = await response.json();
      return geoJson.features[0].geometry.coordinates.map(point =>
        Cesium.Cartesian3.fromDegrees(point[0], point[1], point[2])
      );
    } catch (error) {
      console.error('飞行路径加载失败:', error);
      return [];
    }
  };

  // 2. 配置飞机实体
  const setupAirplane = async (positions) => {
    // 时间系统配置
    const startTime = Cesium.JulianDate.now();
    const stopTime = Cesium.JulianDate.addSeconds(startTime, duration, new Cesium.JulianDate());

    viewer.clock.startTime = startTime.clone();
    viewer.clock.stopTime = stopTime.clone();
    viewer.clock.currentTime = startTime.clone();
    viewer.clock.multiplier = 1;  // 5倍速播放
    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;

    // 位置插值配置
    const positionProperty = new Cesium.SampledPositionProperty();
    positionProperty.setInterpolationOptions({
      interpolationDegree: 3,
      interpolationAlgorithm: Cesium.HermitePolynomialApproximation
    });

    // 添加时间关键点
    const timeStep = duration / (positions.length - 1);
    positions.forEach((position, index) => {
      const time = Cesium.JulianDate.addSeconds(
        startTime,
        index * timeStep,
        new Cesium.JulianDate()
      );
      positionProperty.addSample(time, position);
    });

    // 创建飞机实体
    const airplane = viewer.entities.add({
      availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
        start: startTime,
        stop: stopTime
      })]),
      position: positionProperty,
      orientation: new Cesium.VelocityOrientationProperty(positionProperty),
      model: {
        uri: modelUrl,
        minimumPixelSize: 128,
        maximumScale: 2000,
        runAnimations: false,
        // 方向校准（根据模型实际朝向调整）
        heading: Cesium.Math.toRadians(90),
        pitch: 0,
        roll: 0,
        scale: 2.0
      },
      path: {
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.3,
          color: Cesium.Color.YELLOW
        }),
        width: 10
      }
    });

    // 3. 相机锁定配置
    // viewer.trackedEntity = airplane; // 锁定飞机实体
    viewer.scene.screenSpaceCameraController.enableInputs = false; // 禁用所有相机操作

    // viewer.zoomTo(airplane, new Cesium.HeadingPitchRange( // 缩放到飞机所在范围
    //   Cesium.Math.toRadians(-45),  // 俯视角度
    //   Cesium.Math.toRadians(-30),  // 倾斜角度
    //   2000                        // 跟踪距离
    // ));

    return airplane;
  };

  // 主执行流程
  const positions_2 = await loadFlightPath();
  if (positions_2.length < 2) {
    throw new Error('有效的路径点不足');
  }
  return await setupAirplane(positions_2);
}